Thumb

Part-3:How to Add and Show Markers(Location) in Google Map from database in ASP.NET MVC | Jquery

10/16/2019 7:37:29 AM

Download Project  (Full Project)

Step-1

In this part i will show how to add and show marker (Location) in Google map from database using Jquery. Now  Open visual studio then open our existing project where we are working. First we need to add database. Create a database then the under the database create a table. This table represent this Column “Id”, ”Rating”, ”Address”, ”Lat”,”Long”. Now go to our project and install ado.net entity framework for connect our database. Then get the data from c# controller and pass the view by the return key word. This method returns json data. Also this method calls from index view function using JavaScript code. You can also show the icon from the JavaScript code. Given bellow the index views code:

@{
    ViewBag.Title = "Home Page";
}
<style>
    #map {
        height: 500px;
    }
</style>
<br /><br />
<div>
    <select class="form-control" id="selectedValue" onchange="GoLocation(this.value)">

        <option>--Select--</option>
        @foreach (var item in ViewBag.ListOfDropdown)
        {
            <option value="@item.Id">@item.Address</option>
        }

    </select>
</div>
<br />
<div id="map"></div>

<script>
    var map;
    function initMap(zoomeLevel,latDb,longDb) {
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: latDb!=null?latDb:23.778074, lng:longDb!=null?longDb:90.397514 },
            zoom: zoomeLevel!=null?zoomeLevel:6
        });

       

    }
    function GoLocation(locationId) {
        $.get("/Home/GetAllLocationById?id=" + locationId, function (data, status) {
            var iconName = data.Rating == 1 ? "../Icons/one.png" : data.Rating == 2 ? "../Icons/two.png" : "../Icons/three.png";
            initMap(data.Zoom, data.Lat, data.Long);
            marker = new google.maps.Marker({
                position: { lat: data.Lat, lng: data.Long },
                map: map,
                icon: iconName
            });
            contentString = '<div id="content">' +
                                '<div id="siteNotice">' +
                                '</div>' +
                                '<h1 id="firstHeading" class="firstHeading">' + data.Address + '</h1>' +
                                '<div id="bodyContent">' +
                                '<p><b>' + data.Address + '</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
                                'sandstone rock formation in the southern part of the ' +
                                'Northern Territory, central Australia. It lies 335&#160;km (208&#160;mi) ' +
                                'south west of the nearest large town, Alice Springs; 450&#160;km ';
            infowindow = new google.maps.InfoWindow({
                content: contentString
            });
            google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
                return function () {
                    infowindow.open(map, marker);
                }
            })(marker, i));
            google.maps.event.addListener(marker, 'mouseout', (function (marker, i) {
                return function () {
                    infowindow.close();
                }
            })(marker, i));
        })
    }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDJOZd-P3bAJXBAYtfryQT_GTv61uRehMs&callback=initMap" async defer></script>

Step-2

First we need to create database. Now create database and table also create table property. Given bellow the sql commend code:

USE [TestDb]
GO
/****** Object:  Table [dbo].[google_map]    Script Date: 8/29/2017 12:46:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[google_map](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Rating] [int] NULL,
	[Address] [nvarchar](50) NULL,
	[Lat] [float] NOT NULL,
	[Long] [float] NULL,
	[Zoom] [int] NULL,
 CONSTRAINT [PK_google_map] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step-3

Now data come from controller by using ado.net entity data model. First create the Entities object then access the table by the object. Then the controller responsible to get the data from database and then the data pass the controller by the return key word using json format. Given bellow the controller code:

using GoogleMap.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GoogleMap.Controllers
{
    public class HomeController : Controller
    {
        TestDbEntities context = new TestDbEntities();
        public ActionResult Index()
        {
            ViewBag.ListOfDropdown = context.google_map.ToList();
            return View();
        }
        public JsonResult GetAllLocation()
        {
            var data = context.google_map.ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetAllLocationById(int id)
        {
            var data = context.google_map.Where(x => x.Id == id).SingleOrDefault();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }
}

Step-4

Now build and run the project.

About Teacher

Reza Karim

Software Engineer

More about him